<?php
namespace app\common;
use app\common\Request ;
ini_set("display_errors", "on");
//require_once dirname(__DIR__) . '/api_sdk/vendor/autoload.php';

class Baidu
{
    /*获取token*/
    public function get_access_token(){
        $request=new Request();
        $weChatConf = get_system_config('baidu_certify_config');
        $client_id=$weChatConf['client_id'];
        $client_secret=$weChatConf['client_secret'];
        $token_url="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=".$client_id."&client_secret=".$client_secret;
        $res=$request->http_request($token_url);
        $res=json_decode($res,true);
        return $res['access_token'];
    }

    public function check_id_card($img_url='',$type='front'){
        $request=new Request();
        $token = $this->get_access_token();
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' . $token;
        $bodys = array(
            'id_card_side' => $type,
            'url' => $img_url,
        );
        $res = $request->request_post($url,$bodys);
        $res=json_decode($res,true);
        if($res['image_status']=='normal'){
            if($type=='front'){
                return ['code'=>1,'msg'=>'识别正常','id_card_number'=>$res['words_result']['公民身份号码']['words'],'username'=>$res['words_result']['姓名']['words']];

            }else{
                return ['code'=>1,'msg'=>'识别正常'];
            }
        }else{
            $msg_erro=$this->get_image_status_text($res['image_status']);
            return ['code'=>0,'msg'=>'识别错误,原因:'.$msg_erro];
        }
    }

    protected function get_image_status_text($status_code){
        $text=['normal'=>'识别正常',
            'reversed_side'=>'身份证正反面颠倒',
            'non_idcard'=>'上传的图片中不包含身份证',
            'blurred'=>'身份证模糊',
            'other_type_card'=>'其他类型证照',
            'over_exposure'=>'身份证关键字段反光或过曝',
            'over_dark'=>'身份证欠曝（亮度过低)',
            'unknown'=>'未知状态',

        ];
        return $text[$status_code];
    }

}


